import Text from 'M/UI/Libraries/Text';
import TouchableOpacity from 'M/UI/Libraries/Touchable/TouchableOpacity';
import View from 'M/UI/Libraries/View';
import StyleSheet from 'react-native/Libraries/StyleSheet/StyleSheet';
import {useRef, useState} from 'react';

const Popup = ({component, buttonTop}) => {
  return <View style={[styles.popup, {top: buttonTop}]}>{component}</View>;
};

export default function PopupButton({component, label}) {
  const [popupVisible, setPopupVisible] = useState(false);
  const [name, setName] = useState(label);
  const buttonRef = useRef(null);

  const getButtonTop = () => {
    // 获取button的布局信息
    return buttonRef.current?.getBoundingClientRect().top;
  };

  const onPress = () => {
    // 显示弹出组件
    setPopupVisible(true);
  };

  return (
    <View>
      <TouchableOpacity onPress={onPress}>
        <Text
          style={{
            fontSize: 18,
          }}>
          {name}
        </Text>
      </TouchableOpacity>

      {/* 使用Animated设置top值 */}
      {popupVisible && (
        <Popup component={component} buttonTop={getButtonTop()} />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  popup: {
    position: 'absolute',
    top: 0,
    left: 0,
    height: 300,
    width: 100,
    borderRadius: 10,
    backgroundColor: '#fff',
  },
});
